/*
1. 生成 generated.js：

npx pbjs -t static-module -w commonjs -o electron/main/proto/generated.js electron/main/proto/request.proto electron/main/proto/response.proto electron/main/proto/notification.proto

2. 修改 generated.js：
    // var $protobuf = require("protobufjs/minimal");
    import * as $protobuf from "protobufjs/minimal";

    // module.exports = $root;
    export default $root;
 */

import * as $protobuf from 'protobufjs/minimal';  // 导入 Protobuf

// 导入生成的 Protobuf 根对象
import $root from './generated.js';  // 这应该指向你的 generated.js 文件

// 获取每个消息类型
const { Request } = ($root as any).request;
const { Response } = ($root as any).response;
const { Notification } = ($root as any).notification;

class ProtoMessageHandler {

  // 创建 Request 消息
  static createRequest(id: string, data: Buffer, timestamp: number, dataType: string) {
    return Request.create({
      id,
      data,
      timestamp,
      dataType
    });
  }

  // 编码 Request 消息
  static encodeRequest(requestMessage: any) {
    return Request.encode(requestMessage).finish();
  }

  // 解码 Request 消息
  static decodeRequest(encodedData: Uint8Array) {
    return Request.decode(encodedData);
  }

  // 创建 Response 消息
  static createResponse(id: string, data: Buffer, timestamp: number, dataType: string, errorCode: string) {
    return Response.create({
      id,
      data,
      timestamp,
      dataType,
      error_code: errorCode
    });
  }

  // 编码 Response 消息
  static encodeResponse(responseMessage: any) {
    return Response.encode(responseMessage).finish();
  }

  // 解码 Response 消息
  static decodeResponse(encodedData: Uint8Array) {
    return Response.decode(encodedData);
  }

  // 创建 Notification 消息
  static createNotification(type: number, message: Buffer, timestamp: number) {
    return Notification.create({
      type,
      message,
      timestamp
    });
  }

  // 编码 Notification 消息
  static encodeNotification(notificationMessage: any) {
    return Notification.encode(notificationMessage).finish();
  }

  // 解码 Notification 消息
  static decodeNotification(encodedData: Uint8Array) {
    return Notification.decode(encodedData);
  }
}

export default ProtoMessageHandler;  // 导出封装的类

